package com.hmall.common.interceptor;

import com.hmall.common.utils.UserContext;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 张文接
 * @version 1.0
 * @createTime 2024/7/23 20:56
 */
public class UserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的用户信息
        String userId = request.getHeader("user-info");
        //若不为空，则存入用户上下文中（ThreadLocal）
        if (StringUtils.hasText(userId)) {
            UserContext.setUser(Long.valueOf(userId));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserContext.removeUser();
    }
}
